import React, {Component} from 'react';
import {Grid, Input, Button,Table,Search,Feedback,Switch,Balloon} from "@icedesign/base";
import ReactJson from 'react-json-view';
import IceTitle from '@icedesign/title';
import IceContainer from '@icedesign/container';
import { Tooltip, Whisper } from 'rsuite';
import 'rsuite/dist/styles/rsuite.min.css';
import axios from 'axios';
import JsonUtils from '../../../../tools/JsonUtils'
import './PostMan.scss'

const {Row, Col} = Grid;


export default class PostMan extends Component {

    constructor(props) {
        super(props);
        this.state = {
            url:'/',
            filter: [{text: "POST", value: "post"}, {text: "GET", value: "get"}],
            dataSource: [],
            rowSelection: {
                onChange: this.onChange.bind(this),
                selectedRowKeys: []
            },
            jsonParams:{},
            selected:{},
            respJson:{},
            paramJson:{text: "GET", value: "get"},
            checked:true,
            param:{
                actionName:"",
                method:""
            }
        }
        this.onChange = this.ckOnChange.bind(this);
    }
    onChange(ids, records) {
        console.log(records);
        let { rowSelection } = this.state;
        rowSelection.selectedRowKeys = ids;
        this.setState({ rowSelection });
    }

    ckOnChange(checked) {
        this.setState({ checked:checked });
    }

    componentDidUpdate(){
        if (this.state.param.actionName != this.props.action || this.state.param.method != this.props.method){
            var params = new URLSearchParams();
            params.append('actionName', this.props.action);
            params.append('method', this.props.method);
            params.append('paramType', this.props.paramType);
            this.setState({param:{
                actionName:this.props.action,
                method:this.props.method,
            }});
            axios
                .post('/api/getPostManData',params)
                .then((response) => {
                    this.state.rowSelection.selectedRowKeys = response.data.selectedRowKeys;
                    for (var i of response.data.selectedRowKeys){
                        this.state.selected[i] = {key: i};
                    }
                    this.setState({
                        url:response.data.url,
                        filter:response.data.requestType,
                        dataSource: response.data.reqParams,
                        jsonParams: response.data.jsonParams,
                        rowSelection:this.state.rowSelection,
                        selected:this.state.selected
                    });
                })
                .catch((error) => {
                    Feedback.toast.error(error.msg == undefined?"系统错误":error.msg);
                });
        }
    }

    componentWillMount() {
        var params = new URLSearchParams();
        params.append('actionName', this.props.action);
        params.append('method', this.props.method);
        this.setState({param:{
            actionName:this.props.action,
            method:this.props.method,
        }});
        axios
            .post('/api/getPostManData',params)
            .then((response) => {
                this.state.rowSelection.selectedRowKeys = response.data.selectedRowKeys;
                for (var i of response.data.selectedRowKeys){
                    this.state.selected[i] = {key: i};
                }
                this.setState({
                    url:response.data.url,
                    filter:response.data.requestType,
                    dataSource: response.data.reqParams,
                    jsonParams: response.data.jsonParams,
                    rowSelection:this.state.rowSelection,
                    selected:this.state.selected
                });
            })
            .catch((error) => {
                Feedback.toast.error(error.msg == undefined?"系统错误":error.msg);
            });
    }

    inputKey = (valueKey, value, index, record) => {
        return <Input className="textClsName" style={{width:'100%'}} onChange={this.onTbChange.bind(this,record.id,'key')} defaultValue={record.key} placeholder="key"/>;
    }

    inputDel = (valueKey, value, index, record) =>{
        return record.delflag ? <Button shape="text" style={{width:'100%'}} onClick={this.delNewItem.bind(this,index)}>删除</Button> : "";
    }

    addNewItem = () =>{
        var id = this.getId();
        this.state.dataSource.push({id: id,delflag:true});
        this.state.rowSelection.selectedRowKeys.push(id);
        this.setState({
            dataSource:this.state.dataSource,
            rowSelection:this.state.rowSelection
        })
    }

    delNewItem = (index) =>{
        this.state.dataSource.splice(index, 1);
        this.state.rowSelection.selectedRowKeys.splice(index, 1);
        this.setState({
            dataSource:this.state.dataSource,
            rowSelection:this.state.rowSelection
        })
    }

    //生成随机ID：GUID
    getId = () =>{
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
            var r = Math.random() * 16 | 0,
                v = c == 'x' ? r : (r & 0x3 | 0x8);
            return v.toString(16);
        }).toUpperCase();
    }

    onSearch(value) {
        console.log(value);
        let paramMap = new Map()
        let selected = this.state.selected;
        if (this.state.checked){
            this.state.rowSelection.selectedRowKeys.forEach((item) => {
                var rs = selected[item];
                if (undefined != rs && undefined != rs.key){
                    paramMap.set(rs.key,rs.val == undefined?"":rs.val);
                }
            });
            paramMap = JsonUtils.paramMapToJson(paramMap);
        } else {
            paramMap = JsonUtils.jsonToMap(JSON.stringify(this.state.jsonParams));
        }

        if ("get" == value.filterValue) {
            axios
                .get(this.state.url,{params:JsonUtils.mapToParam(paramMap)})
                .then((response) => {
                    console.log(response.data);
                    this.setState({respJson:response.data,url:value.key})
                })
                .catch((error) => {
                    Feedback.toast.error(error.msg == undefined?"系统错误":error.msg);
                });
        } else {
            axios
                .post(this.state.url,JsonUtils.mapToParam(paramMap))
                .then((response) => {
                    console.log(response.data);
                    this.setState({respJson:response.data,url:value.key})
                })
                .catch((error) => {
                    Feedback.toast.error(error.msg == undefined?"系统错误":error.msg);
                });
        }
    }

    onTbChange = (id,type,value) =>{
        var map = this.state.selected[id];
        if (undefined == map){
            this.state.selected[id] = JSON.parse('{"' + type + '":"' + value + '"}');
        } else {
            map[type] = value;
        }
        this.setState({selected: this.state.selected});
    }

    edit = (ed)=>{
        this.setState({jsonParams: ed.updated_src});
    }
    add = (ed)=>{
        this.setState({jsonParams: ed.updated_src});
    }
    delete = (ed)=>{
        this.setState({jsonParams: ed.updated_src});
    }

    render() {
        const inputVal = (valueKey, value, index, record)=>{
            return <Input className="textClsName" style={{width:'100%'}} onChange={this.onTbChange.bind(this,record.id,'val')}  placeholder="value"/>;
        }
        return (
            <IceContainer>
                <IceTitle text="测试" style={{marginTop:0}}/>
                <div className="demo">
                    <Row className="demo-row" style={{width:'80%',marginLeft:'10%'}}>
                        <Col span="24">
                            <Search ref="send" size={'large'} autoWidth={true} hasIcon={false} searchText={"Send"}
                                    value={this.state.url} filter={this.state.filter}
                                    onSearch = {this.onSearch.bind(this)}
                            />
                        </Col>
                    </Row>
                    <h2>
                        请求参数:
                        <div style={{textAlign:'right',paddingRight:25,float:'right'}} >
                            <Whisper placement="top" trigger="hover" speaker={<Tooltip>json/params</Tooltip>}>
                                <Switch size={"small"} checked={this.state.checked} onChange={this.onChange} />
                            </Whisper>
                        </div>
                    </h2>
                    {
                        this.state.checked?
                            <div>
                                <Table ref="table" dataSource={this.state.dataSource} rowSelection={this.state.rowSelection} hasBorder={false}>
                                    <Table.Column  title="参数名" width={'30%'} cell={this.inputKey.bind(this, 'key')} />
                                    <Table.Column  title="参数值" width={'30%'} cell={inputVal.bind(this,'key')}/>
                                    <Table.Column  title="描述"  width={'30%'} dataIndex={'desc'}/>
                                    <Table.Column  title="操作"  width={'10%'} cell={this.inputDel.bind(this,'delflag')} />
                                </Table>
                                <div onClick={this.addNewItem} style={styles.addNewItem}>
                                    + 新增一行
                                </div>
                            </div>
                        :
                        <ReactJson src={this.state.jsonParams} theme="monokai" style={{borderRadius:5,padding:6}}
                                   onEdit={this.edit} onAdd={this.add} onDelete={this.delete} />
                    }
                    <h2>返回事例:</h2>
                    <ReactJson src={this.state.respJson} theme="monokai" style={{borderRadius:5,padding:6}} />
                </div>
            </IceContainer>
        )
    }
}

const styles = {
    addNewItem: {
        background: '#F5F5F5',
        height: 32,
        lineHeight: '32px',
        marginTop: 20,
        cursor: 'pointer',
        textAlign: 'center',
    },
};